<?php
/**
 * Builds up a programmatic model for SQL ORDER BY clause to be used by SELECT query.
 */
class SQLOrderByClause extends AbstractSQLClause {
	protected $strASC = "ASC";
	protected $strDESC = "DESC";
	/**
	 * Sets up order by fields directly from constructor.
	 * 
	 * @example array("a"=>"ASC","b"=>"DESC")
	 * @param array(string=>string) $tblSorts
	 */
	public function __construct($tblSorts=array()) {
		if(sizeof($tblSorts)) {
			foreach($tblSorts as $key=>$value) {
				if(strtoupper($value)==$this->strASC) {
					$this->addAsc($key);
				} else {
					$this->addDesc($key);
				}
			}
		}
	}
	
	/**
	 * Adds an ASC sort for expression.
	 * 
	 * @example a
	 * 
	 * @param string $key
	 * @return SQLOrderByClause
	 */
	public function addAsc($key) {
		$this->tblContents[$key] = $this->strASC;
		return $this;
	}
	
	/**
	 * Adds an DESC sort for expression.
	 * 
	 * @example b
	 * 
	 * @param string $key
	 * @return SQLOrderByClause
	 */
	public function addDesc($key) {
		$this->tblContents[$key] = $this->strDESC;
		return $this;
		
	}
	
	/**
	 * Transforms clause to string
	 * 
	 * @example a ASC, b DESC
	 * (non-PHPdoc)
	 * @see AbstractSQLClause::toString()
	 */
	public function toString() {
		$output = "";
		foreach($this->tblContents as $strKey=>$strValue) {
			$output .= $strKey.($strValue?" ".$strValue:"").", ";
		}
		return substr($output,0,-2);
	}
}